from telethon import TelegramClient
import asyncio
import time
from telethon.client import account
from Database import get_accounts,delete_old_connections,_delete_all_groups
from Settings import ADMINS
from telethon import errors
class Client(TelegramClient):
    def __init__(self, session, api_id, api_hash, is_active, user_id, wallet):
        super().__init__(session, api_id, api_hash)
        self.id = user_id
        self.wallet = wallet
        self.is_active = bool(is_active)

    @staticmethod
    def get_url_from_button(message):
        return message.reply_markup.rows[0].buttons[0].url

    async def notify_admins(self, message):
        for admin in ADMINS:
            await self.send_message(admin, message)

    async def find_dialog(self, dialog_title):
        dialogs = await self.get_dialogs()
        for dlg in dialogs:

            if dlg.title == dialog_title:
                return dlg
        return None
    async def leave_all_old_groups(self):
        groups_to_leave = delete_old_connections(self)
        if len(groups_to_leave)!=0:
            dialogs = await self.get_dialogs()
            for dlg in dialogs:

                if dlg.title in groups_to_leave:
                    
                    while True:
                        try:
                            await self.delete_dialog(dlg)
                            break
                        except errors.RpcCallFailError as e:
                            print(e)
                            continue
                        except Exception as e:
                            print(e)
                            break
                            
                    await asyncio.sleep(1)
    async def _leave_all_groups(self):
        groups_to_leave =_delete_all_groups(self)
        if len(groups_to_leave)!=0:
            dialogs = await self.get_dialogs()
            for dlg in dialogs:

                if dlg.title in groups_to_leave:
                    try:
                            await self.delete_dialog(dlg)
                            break
                    except errors.RpcCallFailError as e:
                            print(e)
                            continue
                    except Exception as e:
                            print(e)
                            break
                    await asyncio.sleep(1)
    
def create_clients():
    res = []
    

    for el in get_accounts():
        id=el[0]
        phone=el[1]
        password=el[2]
        api_id = el[3]
        api_hash= el[4]
        is_active = int(el[5])
        session = el[6]
        wallet = el[7]
        

        if is_active == 1:
            res.append(Client(session=session, api_id=api_id, api_hash=api_hash, is_active=is_active, wallet=wallet, user_id= id))

    return res

if __name__ == '__main__':
    accounts=get_accounts()
    for account in accounts:
        account._leave_all_groups()